package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private RoomInfoService roomInfoService;


    /**
     * 保存和更新公寓信息·——》
     * 公寓信息根配套，杂费，标签，图片都是多对多关系，当我们需要保存和更新中间表，
     * 当我们更新时，所处理的业务所需是先删除中间表，再保存新的中间表
     */
    @Override
    public void saveAndUpload(ApartmentSubmitVo apartmentSubmitVo) {
        //1.先判断是更新还是保存
        boolean result = apartmentSubmitVo.getId() != null;

        /**
         * 前段没有传省市区内容，手动添加添加城市信息
         */
        //1.插入省份
        ProvinceInfo provinceInfo = provinceInfoService.getById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());
        //2.插入市区
        CityInfo cityInfo = cityInfoService.getById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(cityInfo.getName());
        //3.插入区县
        DistrictInfo districtInfo = districtInfoService.getById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());

        /**
         * 不管怎样保存和更新否需要先对公寓自身的属性进行操作
         */
        //先保存公寓自己单表的信息
        saveOrUpdate(apartmentSubmitVo);

        //获取保存或者更新的公寓id
        Long apartmentId = apartmentSubmitVo.getId();

        //更新
        if (result){
            //1.清除原有的公寓配置
            LambdaQueryWrapper<ApartmentFacility> lambdaQueryApartWrapper = new LambdaQueryWrapper<>();
            lambdaQueryApartWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(lambdaQueryApartWrapper);

            //2.清除公寓标签
            LambdaQueryWrapper<ApartmentLabel> labelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            labelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(labelLambdaQueryWrapper);

            //3.清除杂费
            LambdaQueryWrapper<ApartmentFeeValue> feeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            feeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(feeValueLambdaQueryWrapper);

            //4.删除图片
            LambdaQueryWrapper<GraphInfo> graphLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphLambdaQueryWrapper);

        }
        //保存更新中间表

        /**
         * 根据前段传过来的数据获取插入公寓属性的id集合
         * 创建公寓跟属性的中间表对象装进自定义属性（公寓属性）的集合中
         * 通过mybatis-plus， saveBatch方法直接保存结果集
         */
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<ApartmentFacility> facilityList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().apartmentId(apartmentId).facilityId(facilityInfoId).build();
                facilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(facilityList);
        }
        /**
         * 根据前段传过来的数据获取插入公寓标签的id集合
         * 创建公寓跟标签的中间表对象装进自定义属性（公寓标签）的集合中
         * 通过mybatis-plus， saveBatch方法直接保存结果集
         */
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)){
        List<ApartmentLabel> labelList = new ArrayList<>(labelIds.size());
        for (Long labelId : labelIds) {
            ApartmentLabel apartmentLabel = ApartmentLabel.builder().apartmentId(apartmentId).labelId(labelId).build();
            labelList.add(apartmentLabel);
        }
        apartmentLabelService.saveBatch(labelList);
        }
        /**
         * 根据前段传过来的数据获取插入公寓杂费的id集合
         * 创建公寓跟杂费的中间表对象装进自定义（公寓杂费）的集合中
         * 通过mybatis-plus， saveBatch方法直接保存结果集
         */
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> feeValueList = new ArrayList<>(feeValueIds.size());
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().apartmentId(apartmentId).feeValueId(feeValueId).build();
                feeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(feeValueList);
        }

        /**
         * 根据前段传过来的数据获取插入公寓图片的id集合
         * 创建公寓跟图片的中间表对象装进自定义（公寓图片）的集合中
         * 通过mybatis-plus， saveBatch方法直接保存结果集
         */

        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemId(apartmentId);
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }
    }

    /**
     * 分页查询公寓信息
     * @param page
     * @param queryVo
     */
    @Override
    public void customPage(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.customPage(page,queryVo);
    }

    /**
     * 根据id进行数据查询-》数据的回显
     *
     * 我们通过分别查询公寓信息-配置-标签-杂费-图片信息赋值给返回对象，避免了太复杂的多表联查
     * @return
     */
    @Override
    public ApartmentDetailVo customGetById(Long id) {
        //创建一个对象用于封装返回结果
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //1.查询公寓信息
        ApartmentInfo apartmentInfo = getById(id);
        //BeanUtils对具有相同属性进行赋值，
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);

        //2.查询【配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.customQueryList(id);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);

        //3.查询【标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.customQueryList(id);
        apartmentDetailVo.setLabelInfoList(labelInfoList);

        //4.查询杂费信息
        List<FeeValueVo> feeValueVoList = feeValueMapper.customQueryList(id);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        //5.查询公寓对应的图片信息
        List<GraphVo> graphInfoList = graphInfoMapper.customQueryList(ItemType.APARTMENT,id);
        apartmentDetailVo.setGraphVoList(graphInfoList);


        return apartmentDetailVo;
    }

    /**
     * 根据id删除公寓信息
     * 1.查看公寓下面是否有房间有的话不能删除
     * 2.删除配置-标签-杂费-三个中间表信息》-图片
     * 3.异常处理流派
     * @param id
     */
    @Override
    public void customRemoveById(Long id) {
        //1.判断是否能删除-下面有没有房间
        LambdaQueryWrapper<RoomInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoomInfo::getApartmentId, id);
        long count = roomInfoService.count(queryWrapper);
        //查询到房间就不删除-》抛出自定义异常，交给全局异常处理器处理（不影响正常业务流程，而且可以快速处理，不用一层一层返回）
        if (count > 0) {
            throw  new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        //没有房间删除操作
        //1.删除公寓信息
        removeById(id);
        //2.删除公寓配置中间表相联系信息
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //3.同删除标签信息
        LambdaQueryWrapper<ApartmentLabel> labelInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        labelInfoLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelService.remove(labelInfoLambdaQueryWrapper);

        //4.删除杂费信息
        LambdaQueryWrapper<ApartmentFeeValue> feeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        feeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueService.remove(feeValueLambdaQueryWrapper);

        //5.删除图片
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

    }

}




